package com.hubiao.pay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.hubiao.pay.common.domain.BusinessException;
import com.hubiao.pay.common.domain.CommonErrorCode;
import com.hubiao.pay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Description
 *
 * @author hubiao
 * @since 2020-11-04 20:22
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private RestTemplate restTemplate;

    @Value("${sms.url}")
    private String url;

    @Value("${sms.effectiveTime}")
    private String effectiveTime;


    /**
     * 获取手机验证码
     *
     * @param phone
     * @return
     */
    @Override
    public String sendMsg(String phone) {
        String sms_url = url + "/generate?name=sms&effectiveTime=" + effectiveTime;
        Map<String, Object> mapBody = new HashMap<>();
        mapBody.put( "mobile", phone );
        HttpHeaders headers = new HttpHeaders();
        //指定Content-Type: application/json
        headers.setContentType( MediaType.APPLICATION_JSON );
        //HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) {
        HttpEntity httpEntity = new HttpEntity( mapBody, headers );
        ResponseEntity<Map> exchange = null;
        Map body = null;
        try {
            //发送请求验证码服务，获取验证码
            exchange = restTemplate.exchange( sms_url, HttpMethod.POST, httpEntity, Map.class );
            body = exchange.getBody();
            log.info( "请求验证码服务，获得响应：{}", JSON.toJSONString( exchange ) );
        } catch (RestClientException e) {
            e.printStackTrace();
            throw new RuntimeException( "发送验证码失败" );
        }
        //获取body里面的内容
        if (body == null && body.get( "result" ) == null) {
            throw new RuntimeException( "发送验证码失败" );
        }
        System.out.println( body );
        //获取短信key值
        Map data = (Map) body.get( "result" );
        System.out.println( data );
        //获取key值
        String key = (String) data.get( "key" );
        log.info( "得到发送验证码对应的key:{}", key );
        return key;
    }


    /**
     * 校验验证码服务
     *
     * @param verifyCode 验证码
     * @param verifyKey  验证码key
     */
    @Override
    public void checkVerifyCode(String verifyCode, String verifyKey) throws BusinessException {
        //1.请求的验证码校验服务路径
        String sms_url = url + "/verify?name=sms&verificationCode=" + verifyCode + "&verificationKey=" + verifyKey;
        //2.发送请求验证码服务，获取验证码
        ResponseEntity<Map> exchange = null;
        Map body = null;
        try {
            exchange = restTemplate.exchange( sms_url, HttpMethod.POST, HttpEntity.EMPTY, Map.class );
            body = exchange.getBody();
            log.info( "请求验证码校验服务，获得响应：{}", JSON.toJSONString( exchange ) );
        } catch (RestClientException e) {
            throw new BusinessException( CommonErrorCode.E_100102 );
        }
        //3.判断响应结果
//        {
//                "code": 0,
//                "msg": "",
//                "result": false
//        }
        if (body == null || body.get( "result" ) == null || !(Boolean) body.get( "result" )) {
            throw new BusinessException( CommonErrorCode.E_100102 );
        }
    }
}
